/**
 * websocket类
 * 使用时引入该文件，并new实例
 */
class WebsocketService{
    constructor(url,data){
        this.wsUrl = url || 'ws://127.0.0.1:8001';
        this.wsData = data || {};
        //初始化websocket
        this.wsInit();
    }

    /**
     * 初始化
     */
    wsInit(){
        this.websocket = new WebSocket(this.wsUrl);
        this.websocket.onmessage = this.wsMessage;
        this.websocket.onopen = this.wsOpen;
        this.websocket.onclose = this.wsClose;
        this.websocket.onerror = this.wsError;
    }

    /**
     * 接收数据
     * @param e
     */
    wsMessage(e){
        let result = JSON.parse(e.data);
        console.log(result)
    }

    /**
     * 发送数据
     * @param data
     */
    wsSend(data){
        this.websocket.send(data);
    }

    /**
     * 建立连接成功后，发送数据
     */
    wsOpen(){
        console.log('websocket connect success!');
        console.log(this);
        //ws前后台已连接成功，可以发送数据和接收数据，但是为啥this指向不对啊?????
        this.wsSend(JSON.stringify(this.wsData));
    }

    /**
     * 连接关闭
     * @param e
     */
    wsClose(e){
        console.log(e)
    }

    /**
     * 连接出错，重新初始化
     */
    wsError(){
        this.wsInit();
    }
}

export default WebsocketService
